package mq

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"
)

var (
	// log *logs.Dispatcher
	mq *MQ
)

// MQ 消息队列
type MQ struct {
	running    int
	closed     chan struct{}
	wg         sync.WaitGroup
	dispatcher *Dispatcher
	// webMonitor *WebMonitor
	// serv       IServer
}

// New 新建mq
func New() *MQ {
	mq = &MQ{
		closed: make(chan struct{}),
	}
	mq.dispatcher = NewDispatcher()
	// mq.webMonitor = NewWebMonitor()
	// mq.serv = NewServ()

	return mq
}

// Run 启动mq
func (mq *MQ) Run(host, port, password string, maxIDle, maxActive int) {
	if mq.running == 1 {
		fmt.Println("running.")
		return
	}
	ctx, cannel := context.WithCancel(context.Background())
	defer cannel()
	mq.running = 1

	// mq.initLogger()

	mq.initRedisPool(host, port, password, maxIDle, maxActive)
	mq.initSignalHandler(cannel)

	fmt.Println("Welcome to use mq, enjoy it")

	go mq.dispatcher.Run(ctx) // job调度服务
	// go mq.webMonitor.Run(ctx) // web监控服务
	// go mq.serv.Run(ctx)       // rpc服务或http服务

	<-mq.closed
	fmt.Println("Closed.")
}

func (mq *MQ) initRedisPool(host, port, password string, maxIDle, maxActive int) {
	Redis.InitPool(host, port, password, maxIDle, maxActive)
}

// initSignalHandler 平滑关闭
func (mq *MQ) initSignalHandler(cannel context.CancelFunc) {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
	go func() {
		<-sigs
		cannel()                // 通知各个服务退出
		mq.wg.Wait()            // 等待各个服务退出
		mq.closed <- struct{}{} // 关闭整个服务
		Redis.Pool.Close()      // 关闭redis连接池
		mq.running = 0
	}()
}
